<?php
namespace Web\Controller;
use Think\Controller;

class ProjectController extends BaseController {
    public function index(){
        if(session('roleid') != 1){
            $map['user_id'] = session(C('SESSION_ADMIN_ID'));
            $project_ids = M('project_user')->where($map)->getField('project_id', true);
            if($project_ids){
                $map['p.id'] = array('in', $project_ids);
            }

            //包含演示项目
            $map['demo'] = 1;
            $map['_logic'] = 'OR';
        }
        
        $list = M('project')->alias('p')
            ->join(C('DB_PREFIX').'member m ON p.user_id=m.userid')
            ->where($map)
            ->field('p.*,m.username,m.image_url')
            ->order('p.id desc')
            ->select();

        $pids = array_column($list, 'id');

        if($pids) {
            $cond['project_id'] = array('in', $pids);

            //楼层数
            $rs = M('project_floor')->where($cond)->field('count(*) as num,project_id')->group('project_id')->select();
            $floor_nums = array_column($rs, 'num', 'project_id');

            //设备数
            $rs = M('project_device')->where($cond)->field('count(*) as num,project_id')->group('project_id')->select();
            $device_nums = array_column($rs, 'num', 'project_id');
            //传感器数
            $sensor_nums = array();
            foreach($pids as $pid){
                $sensor_nums[$pid] = $this->getSensorNum($pid);
            }

            //项目拥有者头像
            $own_headpics = array();
            foreach($list as $v){
                $own_headpics[] = array(
                    'project_id'=>$v['id'],
                    'username'=>$v['username'],
                    'image_url'=>$v['image_url'],
                );
            }

            //协同用户头像
            $map2['project_id'] = array('in', $pids);
            $xitong_headpics = M('project_user')->alias('pu')
                ->join(C('DB_PREFIX').'member m ON pu.user_id=m.userid')
                ->where($map2)
                ->field('project_id,username,image_url')
                ->select();

            $all_pics = array_merge($own_headpics, $xitong_headpics);
            
            $headpics = array();
            foreach($all_pics as $v){
                $headpics[$v['project_id']][] = $v;
            }
        }

        $this->assign('list', $list);
        $this->assign('floor_nums', $floor_nums);
        $this->assign('device_nums', $device_nums);
        $this->assign('sensor_nums', $sensor_nums);
        $this->assign('headpics', $headpics);
        $this->assign('userid', session(C('SESSION_ADMIN_ID')));
        $this->assign('username', session(C('SESSION_ADMIN_NAME')));
        $this->display();
    }
    
    public function detail($id=0){
        $vo = M('project')->find($id);

        $uid = session(C('SESSION_ADMIN_ID'));
        if(!$this->isProjectAdmin($id)){
            $uid = M('project')->where(array('id'=>$id))->getField('user_id');
        }

        $cond['userid'] = $uid;
        $module_ids = M('member')->where($cond)->getField('module_ids'); 
        
        $modules = '';
        if($module_ids){
            //$cond['id'] = array('in', $module_ids);
            $modules = M('tpl_module')->where(array('id'=>$module_ids))->getField('id,name');
        }

        //协同用户
        $helpers = M('project_user')->alias('u')
            ->join(C('DB_PREFIX').'member m ON u.user_id=m.userid')
            ->field('m.userid,m.username,m.image_url,m.is_online')
            ->where(array('project_id'=>$id))
            ->select();
        
        //设备数
        $device_num = M('project_device')->where(array('project_id'=>$id))->count();

        //楼层数
        $floor_num = M('project_floor')->where(array('project_id'=>$id))->count();

        $design_count = M('project_version')->where(array('project_id'=>$id))->count();

        $this->assign('pvo', $vo);
        $this->assign('modules', $modules);
        $this->assign('helpers', $helpers);
        $this->assign('design_count', $design_count);
        $this->assign('device_num', $device_num);
        $this->assign('floor_num', $floor_num);
        $this->assign('userid', session(C('SESSION_ADMIN_ID')));
        $this->display();
    }

    public function editProject($id=0){
        $uid = session(C('SESSION_ADMIN_ID'));
        if(IS_POST){
            $Project = M('project');
            $act = I('act', 'add');
            if($act == 'add'){
                if(!$this->isAdmin($uid)) exit('<script>parent.notify("error","提示","您不是管理员，无法创建项目！");</script>');
                $project_num = M('member')->where(array('userid'=>$uid))->getField('project_num');
                $count = $Project->where(array('user_id'=>$uid))->count();
                if($count >= $project_num) exit('<script>parent.notify("error","提示","项目数量超出允许数量！");</script>');
            }

			$rules = array(
                array('project_code','require','项目编号必填！'),
                array('project_code','','项目编号已经存在！',0,'unique'),
                array('project_name','require','项目名称必填！'),
                array('project_addr','require','项目地址必填！'),
                array('floor','require','楼层必选！'),
                array('module_ids','require','设计模版必选！'),
           );
			
			if (!$Project->validate($rules)->create()){
				 exit('<script>parent.notify("error","提示","' . $Project->getError() . '");</script>');
			}else{

                $Project->updated_at = date('Y-m-d H:i:s');

				if($act == 'add'){
                    $classes = array('bg-primary','bg-pink','bg-success','bg-dark');
                    $color = $classes[mt_rand(0,3)];
                    $Project->user_id = session(C('SESSION_ADMIN_ID'));
                    $Project->color = $color;
                    $Project->created_at = date('Y-m-d H:i:s');
                    $ins = $Project->add();
                    writeLog(session(C('SESSION_ADMIN_ID')), 2, '创建项目', '', $ins);
				} else {
                    $ins = $Project->save();
                    writeLog(session(C('SESSION_ADMIN_ID')), 2, '修改项目', '', I('id'));
				}
			}

			if($ins !== false){
				echo '<script>parent.notify("success","提示","项目保存成功！");parent.location="' . U('index') . '";</script>';
			} else {
				echo '<script>parent.notify("error","提示","项目保存失败！");</script>';
			}
		} else {
            $vo = M('project')->find($id);

            $uid = session(C('SESSION_ADMIN_ID'));
            if($id != 0){
                if(!$this->isProjectAdmin($id)){
                    $uid = M('project')->where(array('id'=>$id))->getField('user_id');
                }
            }

            $cond['userid'] = $uid;
            $module_ids = M('member')->where($cond)->getField('module_ids'); 
            
            $modules = '';
            if($module_ids){
                //$cond['id'] = array('in', $module_ids);
                $modules = M('tpl_module')->where(array('id'=>$module_ids))->getField('id,name');
            }

			$this->assign('vo', $vo);
			$this->assign('modules', $modules);
			$this->display();
		}
    }

    public function delProject($id=0){
        $vo = M('project')->where(array('id'=>$id))->field('user_id,project_name')->find();
        if(session(C('SESSION_ADMIN_ID')) != $vo['user_id']) exit('0');
        M('project')->delete($id);
        M('project_user')->where(array('project_id'=>$id))->delete();
        M('project_device')->where(array('project_id'=>$id))->delete();
        M('project_device_sensor_param')->where(array('project_id'=>$id))->delete();
        M('project_design')->where(array('project_id'=>$id))->delete();
        M('project_floor')->where(array('project_id'=>$id))->delete();
        writeLog(session(C('SESSION_ADMIN_ID')), 2, '删除'.$vo['project_name'].'项目', '', $id);
        echo '1';
    }

    public function copyProject($id=0){
        $vo = M('project')->find($id);
        $data['project_code'] = 'P'.time();
        $data['project_name'] = $vo['project_name'].'_Copy';
        $data['project_addr'] = $vo['project_addr'];
        $data['project_progress'] = $vo['project_progress'];
        $data['intro'] = $vo['intro'];
        $data['module_ids'] = $vo['module_ids'];
        $data['user_id'] = session(C('SESSION_ADMIN_ID'));
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        $ins = M('project')->add($data);
        if($ins){
            //复制设备
            $data = M('project_device')->where(array('project_id'=>$id))->select();
            $cpns = $new_cpns = $new_ids = array();
            foreach($data as &$v){
                $cpns[$v['cpn_sn']] = $v['id'];

                $v['project_id'] = $ins;
                $v['user_id'] = session(C('SESSION_ADMIN_ID'));
                $v['created_at'] = date('Y-m-d H:i:s');
                $v['updated_at'] = date('Y-m-d H:i:s');
                unset($v['id']);     
            }
            M('project_device')->addAll($data);
            $new_cpns = M('project_device')->where(array('project_id'=>$ins))->field('id,cpn_sn')->select();
            foreach($new_cpns as $v){
                $new_ids[$cpns[$v['cpn_sn']]] = $v['id'];
            }
            //设计成果
            $data = M('project_design')->where(array('project_id'=>$id))->select();
            foreach($data as &$v){
                $v['project_id'] = $ins;
                $v['project_device_id'] = $new_ids[$v['project_device_id']];
                $v['user_id'] = session(C('SESSION_ADMIN_ID'));
                $v['created_at'] = date('Y-m-d H:i:s');
                $v['updated_at'] = date('Y-m-d H:i:s');
                unset($v['id']);
            }
            M('project_design')->addAll($data);
            //设计成果传感器参数
            $data = M('project_device_sensor_param')->where(array('project_id'=>$id))->select();
            foreach($data as &$v){
                $v['project_id'] = $ins;
                $v['device_id'] = $new_ids[$v['device_id']];;
                unset($v['id']);
            }
            M('project_device_sensor_param')->addAll($data);
            //复制楼层
            $data = M('project_floor')->where(array('project_id'=>$id))->select();
            foreach($data as &$v){
                $v['project_id'] = $ins;
                unset($v['id']);
            }
            M('project_floor')->addAll($data);
        }
        writeLog(session(C('SESSION_ADMIN_ID')), 2, '复制'.$vo['project_name'].'项目', '', $ins);
        echo '1';
    }

    public function getGroupCode($sys_code=0){

        $map['sys_type'] = $sys_code;
        $list = M('cpn_class_group')->where($map)->field('group_code,group_name,cpn_type')->order('cpn_type,group_code')->select();
        $group_codes = array();
        foreach($list as $v){
            $group_codes[$v['cpn_type'].','.$v['group_code']] = $v['group_name'];
        }

        $this->ajaxReturn($group_codes);
    }

    public function getModule($id=0){
        $uid = session(C('SESSION_ADMIN_ID'));
        if(!$this->isProjectAdmin($id)){
            $uid = M('project')->where(array('id'=>$id))->getField('user_id');
        }

        $map['userid'] = $uid;
        $module_ids = M('member')->where($map)->getField('module_ids'); 
      
        $results = array();
        if($module_ids){
            $cond['id'] = array('in', $module_ids);
            $list = M('tpl_module')->where($cond)->field('id,name')->select();

            $results = array_map(function($v){
                return array('id'=>$v['id'], 'text'=>$v['name']);
            }, $list);
        }

		$this->ajaxReturn(compact('results'));
    }

	public function getSelModule(){
        $id = I('id', 0);

		$results = array();

		$module_ids = M('project')->where(array('id'=>$id))->getField('module_ids');
		if(empty($module_ids)) $this->ajaxReturn(compact('results'));

		$map['module_ids'] = array('in', $module_ids);
		$list = M('tpl_module')->where($map)->field('id,name')->select();
		$results = array_map(function($v){
			return array('id'=>$v['id'], 'text'=>$v['name']);
		}, $list);

		$this->ajaxReturn(compact('results'));
    }

    public function getCpnList($project_id=0){
        $demo = M('project')->where(array('id'=>$project_id))->field('user_id,demo')->find();
        $map['d.project_id'] = $project_id;
        $list = M('project_device')->alias('d')
            ->join('LEFT JOIN '.C('DB_PREFIX').'cpn_class_group c ON d.cpn_type=c.cpn_type AND d.group_code=c.group_code')
            ->join('LEFT JOIN '.C('DB_PREFIX').'project_floor f ON d.floor=f.floor AND f.project_id='.$project_id)
            ->field('d.*,c.group_name,f.floor_name,exists(select 1 from '.C('DB_PREFIX').'project_design pd where pd.project_device_id=d.id) as status')
            ->where($map)
            ->order('d.sort IS NULL,d.sort,d.id')
            ->select();
        
        $data['data'] = array_map(function($k,$v) use($demo){

            $url = U('setdevice', array('id'=>$v['id']));
            //<a class="setdevice" href="javascript:;" data-id="{$v['id']}" data-type="{$v['cpn_type']}">
            if($demo['demo'] == 1 && $demo['user_id'] != session(C('SESSION_ADMIN_ID'))){
                $action = '<button type="button" class="btn btn-outline-secondary btn-sm"><a href="'.$url.'"><i class="far fa-calendar-alt"></i></a></button>';
            } else {
                $action = <<<EOT
<a class="btn btn-outline-secondary btn-sm lnk" href="{$url}"><i class="far fa-calendar-alt"></i></a>
<button type="button" class="btn btn-outline-secondary btn-sm" data-toggle="modal" data-target="#addDevice" data-id="{$v['id']}">
<a href="#"><i class="far fa-edit"></i></a>
</button>
<a class="btn btn-outline-secondary btn-sm lnk" href="javascript:copyDevice({$v['id']})" alt="配置设备"><i class="far fa-copy"></i></a>
<a class="btn btn-outline-secondary btn-sm lnk" href="javascript:delDevice({$v['id']})" alt="删除设备"><i class="far fa-trash-alt"></i>
EOT;
            }

            //return array($k + 1, $v['cpn_sn'], $v['device_sn'], $v['floor_name'], $v['class_name'], $v['status'] ? '<span class="badge badge-soft-success">已配置</span>' : '<span class="badge badge-soft-danger">未配置</span>', $action);
            return array(
                'checkbox'=>'<input type="checkbox" class="chk chk_'.$v['cpn_type'].'_'.$v['group_code'].'" data-type="'.$v['cpn_type'].'_'.$v['group_code'].'" value="'.$v['id'].'">',
                'rid'=>$v['id'],
                'id'=>$k + 1,
                'cpn_sn'=>$v['cpn_sn'],
                'device_sn'=>$v['device_sn'],
                'floor_name'=>$v['floor_name'],
                'group_name'=>$v['group_name'],
                'status'=>$v['status'] ? '<span class="badge badge-soft-success">已配置</span>' : '<span class="badge badge-soft-danger">未配置</span>',
                'action'=>$action,
            );
		}, array_keys($list), $list);

        $this->ajaxReturn($data);
    }

    public function editDevice($id=0){
        if(IS_POST){
			$act = I('act', 'add');
			$rules = array(
                array('cpn_sn','require','CPN编号必填！'),
                //array('cpn_sn','','CPN编号已经存在！',0,'unique'),
                array('device_sn','require','被控设备编号必填！'),
                array('sys_type','require','机电系统类型必选！'),
                array('project_id','require','项目ID必须存在！'),
           );
			
			$ProjectCpn = M('project_device');
			if (!$ProjectCpn->validate($rules)->create()){
				 exit('<script>parent.notify("error","提示","' . $ProjectCpn->getError() . '");</script>');
			}else{
                if($act == 'edit') $map['id'] = array('neq', I('id'));
                $map['project_id'] = I('project_id');
                $map['cpn_sn'] = I('cpn_sn');
                $did = $ProjectCpn->where($map)->getField('id');
                if($did) exit('<script>parent.notify("error","提示","CPN编号已经存在！");</script>');

                $group_code_arr = explode(',', I('group_code'));
                if($group_code_arr){
                    $ProjectCpn->cpn_type = $group_code_arr[0];
                    $ProjectCpn->group_code = $group_code_arr[1];
                }

                $ProjectCpn->updated_at = date('Y-m-d H:i:s');
                $ProjectCpn->user_id = session(C('SESSION_ADMIN_ID'));

				if($act == 'add'){
                    $ProjectCpn->created_at = date('Y-m-d H:i:s');
                    $ins = $ProjectCpn->add();
                    writeLog(session(C('SESSION_ADMIN_ID')), 2, '增加设备 - '.I('cpn_sn'), '', I('project_id'));
				} else {
                    $ins = $ProjectCpn->save();
                    writeLog(session(C('SESSION_ADMIN_ID')), 2, '修改设备 - '.I('cpn_sn'), '', I('project_id'));
				}
			}

			if($ins !== false){
                //table.ajax.reload( null, false ); // user paging is not reset on reload
				echo '<script>parent.notify("success","提示","设备保存成功！");parent.$("#addDevice").modal("hide");parent.table.ajax.reload();</script>';
			} else {
				echo '<script>parent.notify("error","提示","设备保存失败！");</script>';
			}
		} else {
            $vo = M('project_device')->find($id);

            $sys_codes = M('cpn_class_sys')->getField('sys_code,sys_name');
            //$cpn_classes = M('cpn_class')->where(array('is_show'=>1))->getField('class_id,class_name');

            $map['sys_type'] = $vo['sys_type'];
            $list = M('cpn_class_group')->where($map)->field('group_code,group_name,cpn_type')->order("cpn_type,group_code")->select();
            $group_codes = array();
            foreach($list as $v){
                $group_codes[$v['cpn_type'].','.$v['group_code']] = $v['group_name'];
            }

            $floors = M('project_floor')->where(array('project_id'=>I('project_id')))->getField('floor,floor_name');

            //$this->assign('cpn_classes', $cpn_classes);
            $this->assign('sys_codes', $sys_codes);
            $this->assign('group_codes', $group_codes);
            $this->assign('floors', $floors);
            $this->assign('vo', $vo);
			$this->display();
		}
    }

    public function copyDevice($id=0){
        $vo = M('project_device')->find($id);
        $data['project_id'] = $vo['project_id'];
        $data['cpn_sn'] = $vo['cpn_sn'].'_copy';
        $data['device_sn'] = $vo['device_sn'];
        $data['floor'] = $vo['floor'];
        $data['sys_type'] = $vo['sys_type'];
        $data['cpn_type'] = $vo['cpn_type'];
        $data['group_code'] = $vo['group_code'];
        $data['intro'] = $vo['intro'];
        $data['user_id'] = session(C('SESSION_ADMIN_ID'));
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        $ins = M('project_device')->add($data);
        if($ins){
            //复制选型结果
            $data = $tmp = array();
            $list = M('project_design')->where(array('project_id'=>$vo['project_id'],'project_device_id'=>$id))->select();
            foreach($list as $v){
                $tmp['project_id'] = $vo['project_id'];
                $tmp['project_device_id'] = $ins;
                $tmp['param_id'] = $v['param_id'];
                $tmp['user_id'] = session(C('SESSION_ADMIN_ID'));
                $tmp['created_at'] = date('Y-m-d H:i:s');
                $tmp['updated_at'] = date('Y-m-d H:i:s');
                $data[] = $tmp;
            }
            M('project_design')->addAll($data);

            //复制传感器参数
            $data = $tmp = array();
            $list = M('project_device_sensor_param')->where(array('project_id'=>$vo['project_id'],'device_id'=>$id))->select();
            foreach($list as $v){
                $tmp['project_id'] = $vo['project_id'];
                $tmp['device_id'] = $ins;
                $tmp['sensor_code'] = $v['sensor_code'];
                $tmp['sensor_type_group'] = $v['sensor_type_group'];
                $tmp['sensor_param_id'] = $v['sensor_param_id'];
                $tmp['value'] = $v['value'];
                $data[] = $tmp;
            }
            M('project_device_sensor_param')->addAll($data);

            writeLog(session(C('SESSION_ADMIN_ID')), 2, '复制'.$vo['cpn_sn'].'设备', '', $vo['project_id']);
            echo '1';
        } else {
            echo '0';
        }
    }

    public function delDevice($id=0){
        M('project_device')->delete($id);
        M('project_device_sensor_param')->where(array('device_id'=>$id))->delete();
        M('project_design')->where(array('project_device_id'=>$id))->delete();
        echo '1';
    }

    public function cancelHelp($id=0){
        $map['project_id'] = $id;
        $map['user_id'] = session(C('SESSION_ADMIN_ID'));
        M('project_user')->where($map)->delete();
        echo '1';
    }

    public function editFloor($project_id = 0){
        $Floor = M('project_floor');
		if(IS_POST){
            $data = I('data/a');

            foreach($data as $obj){
                if(empty(trim($obj['floor_name']))) exit('<script>parent.notify("error","提示","楼层名为空！");</script>');
                if(empty(trim($obj['floor']))) exit('<script>parent.notify("error","提示","楼层号为空！");</script>');

                $map['project_id'] = $project_id;
                $map['floor'] = $obj['floor'];
                if($obj['id']){
                    $map['id'] = array('neq', $obj['id']);
                }
                $fid = $Floor->where($map)->getField('id');
                if($fid) exit('<script>parent.notify("error","提示","楼层号已经存在！");</script>');

                $map1['project_id'] = $project_id;
                $map1['floor_name'] = $obj['floor_name'];
                if($obj['id']){
                    $map1['id'] = array('neq', $obj['id']);
                }

                $fid = $Floor->where($map1)->getField('id');
                if($fid) exit('<script>parent.notify("error","提示","楼层名已经存在！");</script>');
                
                $tmp = array();
                $tmp['project_id'] = $project_id;
                if($obj['id'] == 0){
                    $tmp['floor_name'] = $obj['floor_name'];
                    $tmp['floor'] = $obj['floor'];
                    $Floor->add($tmp);
                } else {
                    $tmp['id'] = $obj['id'];
                    $tmp['floor_name'] = $obj['floor_name'];
                    $tmp['floor'] = $obj['floor'];
                    $Floor->save($tmp);
                }
            }

            exit('<script>parent.notify("success","提示","保存成功！");parent.location.reload();</script>');
        } else {
            $map['project_id'] = $project_id;
            $list = $Floor->where($map)->select();

            //是否演示项目
            $demo = M('project')->where(array('id'=>$project_id))->field('user_id,demo')->find();

			$this->assign('list', $list);
            $this->assign('demo', $demo);
            $this->assign('userid', session(C('SESSION_ADMIN_ID')));
			$this->display();
        }

    }
    
    public function delFloor($id=0){
        M('project_floor')->delete($id);
        echo '1';
    }

    public function setdevice($id=0){

        $map['d.id'] = $id;
        $dvo = M('project_device')->find($id);
        //是否演示项目
        $demo = M('project')->where(array('id'=>$dvo['project_id']))->field('user_id,demo')->find();

        //判断是否保存过选型
        $did = M('project_design')->where(array('project_device_id'=>$id))->getField('id');
        $is_save = $did ? 1 : 0;

        $list = M('project_device')->alias('d')
            ->join(C('DB_PREFIX').'project p ON d.project_id=p.id')
            ->join(C('DB_PREFIX').'tpl_module_template t ON p.module_ids=t.module_id AND t.cpn_type=d.cpn_type AND t.group_code=d.group_code')
            ->join(C('DB_PREFIX').'tpl_module_template_param tp ON t.id=tp.template_id')
            ->join(C('DB_PREFIX').'device_class_param cp ON tp.device_param_id=cp.id')
            ->join('LEFT JOIN '.C('DB_PREFIX').'device_sensor s ON cp.sensor_type=s.sensor_code')
            ->join('LEFT JOIN '.C('DB_PREFIX').'device_control c ON cp.control_type=c.control_code')
            ->field('cp.*,s.sensor_name,s.is_count,s.sorts as sensor_sorts,c.control_name,c.sorts as control_sorts,tp.is_select')
            ->where($map)
            ->order('tp.id')
            ->select();

        //$sensors = M('device_sensor')->getField('sensor_code,sensor_name');
        //$controls = M('device_control')->getField('control_code,control_name');
        $lists = array();
        foreach($list as $v){
            $lists[$v['sensor_name'].'~'.$v['sensor_type']][$v['sensor_type_group']][] = $v;
        }

        //默认传感器参数
        $sensors_codes = array_unique(array_column($list, 'sensor_type'));
        if($sensors_codes) $map1['sensor_code'] = array('in', $sensors_codes);
        $param_list = M('device_sensor_param')->where($map1)->select();

        $param_default = array();
        foreach($param_list as $p){
            $param_default[$p['sensor_code']][] = $p;
        }

        //传感器参数
        $cond['device_id'] = $id;
        $plist = M('project_device_sensor_param')->alias('p')
            ->join(C('DB_PREFIX').'device_sensor_param sp ON p.sensor_param_id=sp.id')
            ->field('sp.id,sp.sensor_param_name,sp.sensor_param_value,sp.sensor_param_range,sp.sensor_param_unit,p.sensor_code,p.sensor_type_group,p.value')
            ->where($cond)
            ->order('sp.id')
            ->select();

        $sensors_params = array();
        foreach($plist as $p){
            $sensors_params[$p['sensor_code'].'_'.$p['sensor_type_group']][] = $p;
        }

        //显示保存选型记录
        if($is_save){
            $map1['project_device_id'] = $id;
            $save_param_ids = M('project_design')->where($map1)->getField('param_id', true);
        }

        //获取CPN的类型
        $cpn_controller = M('project_device')->alias('d')
            ->join(C('DB_PREFIX').'project p ON d.project_id=p.id')
            ->join(C('DB_PREFIX').'tpl_module_template mt ON p.module_ids=mt.module_id AND mt.cpn_type=d.cpn_type AND mt.group_code=d.group_code')
            ->where(array('d.id'=>$id))
            ->getField('mt.cpn');

        $this->assign('lists', $lists);
        //$this->assign('sensors', $sensors);
        //$this->assign('controls', $controls);
        $this->assign('sensors_params', $sensors_params);
        $this->assign('param_default', $param_default);
        $this->assign('rs', $rs);
        $this->assign('is_save', $is_save);
        $this->assign('save_param_ids', $save_param_ids);
        $this->assign('names', array_unique($names));
        $this->assign('cpn_controller', $cpn_controller);
        $this->assign('dvo', $dvo);
        $this->assign('demo', $demo);
        $this->assign('userid', session(C('SESSION_ADMIN_ID')));
        $this->display();
    }

    public function saveDesign(){
        $id = I('id', 0);
        $cpns_t = explode(',', I('cpns'));
        $cpns_t[] = $id;
        $cpns = array_unique($cpns_t);

        $param_ids = I('param_id/a');
        $project_id = M('project_device')->where(array('id'=>$id))->getField('project_id');

        $Design = M('project_design');
        $data = $tmp = array();
        foreach($cpns  as $device_id){
            foreach($param_ids as $param_id){
                $tmp['project_id'] = $project_id;
                $tmp['project_device_id'] = $device_id;
                $tmp['param_id'] = $param_id;
                $tmp['user_id'] = session(C('SESSION_ADMIN_ID'));
                $tmp['created_at'] = date('Y-m-d H:i:s');
                $tmp['updated_at'] = date('Y-m-d H:i:s');
                $data[] = $tmp;
            }
        }

        if($data) {
            $cond['project_id'] = $project_id;
            $cond['project_device_id'] = array('in', $cpns);
            $Design->where($cond)->delete();
            $Design->addAll($data);
            //保存传感器参数
            $data = $tmp = $json = $arr = array();
            foreach($_POST as $k=>$v){
                if(strpos($k, 'canshu_') !== -1){
                    $arr = explode('_', $k);
                    $json = json_decode($v, true);
                    foreach($cpns  as $device_id){
                        foreach($json as $vv){
                            $tmp['project_id'] = $project_id;
                            $tmp['device_id'] = $device_id;
                            $tmp['sensor_code'] = $arr[1];
                            $tmp['sensor_type_group'] = $arr[2];
                            $tmp['sensor_param_id'] = $vv['id'];
                            $tmp['value'] = $vv['value'];
                            $data[] = $tmp;
                        }
                    }
                }
            }
  
            if($data){
                $map['project_id'] = $project_id;
                $map['device_id'] = array('in', $cpns);
                M('project_device_sensor_param')->where($map)->delete();
                M('project_device_sensor_param')->addAll($data);
            }
           
            exit('<script>parent.notify("success","提示","保存成功！");</script>');
        } else {
            exit('<script>parent.notify("error","提示","没有选择数据！");</script>');
        }
    }

    public function getLogs($id=0){
        //获取操作记录
        $Log = M('log');
        $map['project_id'] = $id;
        $count = $Log
            ->where($map)
            ->count();

        $p = $this->getpage($count,10);
        $page_tpl = urlencode('[PAGE]'); 
        $p->url = "javascript:server($page_tpl)";

        //产生分页信息
        $show  = $this->bootstrap_page_style($p->show());
        
        $list = M('log')->alias('l')
            ->join(C('DB_PREFIX').'member m ON l.userid=m.userid')
            ->field('m.username,m.image_url,l.*')
            ->where($map)
            ->order('id desc')
            ->limit($p->firstRow, $p->listRows)
            ->select();

        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    public function queryUser(){
        $project_id = I('project_id', 0);
        $username = I('username','','trim');
        $content = '<p></p>';
        if($username){
            $map['username'] = array('like', "%{$username}%");
            $map['userid'] = array('neq', session(C('SESSION_ADMIN_ID')));
            $map['_string'] = "userid not in (select user_id from ".C('DB_PREFIX')."project_user where project_id={$project_id})";
            $list = M('member')->where($map)->field('userid,username,image_url')->select();

            $content = '<div></div>';
            foreach($list as $vo){
                $headpic = $vo['image_url'] ? '__ROOT__'.$vo['image_url'] : '__PUBLIC__/assets/images/users/user-0.jpg';
                $content .= <<<EOT
<a class="mr-2 invitetip" href="#" data-toggle="tooltip" data-placement="top" title="{$vo['username']}">
    <img src="{$headpic}" alt="{$vo['username']}" class="rounded-circle thumb-md">
    <div class="text-center mt-1 ">
        <button class="btn btn-xs btn-success yaoqing" data-userid="{$vo['userid']}">邀请</button>
    </div>
</a>
EOT;
            }
        }
        $this->show($content);
    }

    public function invite(){
        $project_id = I('project_id');
        $userid = I('userid');

        $project_name = M('project')->where(array('id'=>$project_id))->getField('project_name');
        $username = session(C('SESSION_ADMIN_NAME'));

        $res = addMessage($userid, "项目【{$project_name}】邀请你加入设计", "$username 邀请你加入项目【{$project_name}】设计。", $project_id);

        /*
        $ProjectUser = M('project_user');

        $map['project_id'] = $project_id;
        $map['user_id'] = $userid;
        $id = $ProjectUser->where($map)->getField('id');

        $data['project_id'] = $project_id;
            $data['user_id'] = $userid;
            $data['admin'] = session(C('SESSION_ADMIN_ID'));
            $data['created_at'] = date('Y-m-d H:i:s');

        if($id){
            $data['id'] = $id;
            $res = $ProjectUser->save($data);
        } else {
            $res = $ProjectUser->add($data);
        }
        */

        if($res){
            echo '1';
        } else {
            echo '0';
        }
        
    }

    public function getSensorParam($sensor_type){
        $map['sensor_code'] = $sensor_type;
        $list = M('device_sensor_param')->where($map)->field('id,sensor_param_name,sensor_param_value,sensor_param_range,sensor_param_unit')->select();
        $this->ajaxReturn($list);
    }

    //显示统计信息
    public function tongji($project_id){
        $clist = getProjectControl($project_id);
        $slist = getProjectSensor($project_id);

        $this->assign('clist', $clist);
        $this->assign('slist', $slist);
        $this->display();
    }

    //更新项目信息
    public function updateProfile(){
        $rules = array(
            array('project_code','require','项目编号必填！'),
            array('project_code','','项目编号已经存在！',0,'unique'),
            array('project_name','require','项目名称必填！'),
            array('project_addr','require','项目地址必填！'),
       );
        
        $Project = M('project');
        if (!$Project->validate($rules)->create()){
             exit(json_encode(array('status'=>0, 'info'=>$Project->getError())));
        }else{
            $data['id'] = I('id');
            $data['project_code'] = I('project_code');
            $data['project_name'] = I('project_name');
            $data['project_addr'] = I('project_addr');
            $data['project_progress'] = I('project_progress');
            $data['module_ids'] = I('module_ids');
            $data['intro'] = I('intro');

            if($_FILES['file']['size'] > 0){
                $dir = dirname(THINK_PATH).'/Uploads/project';

                if(!is_dir($dir)){
                    if (!mkdir($dir, 0777, true)) {
                        $msg['status'] = 0;
                        $msg['info'] = '建立目录失败！';
                        echo json_encode($msg);
                        exit;
                    }
                }

                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =     3145728 ;// 设置附件上传大小
                $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
                $upload->rootPath  =     './Uploads/project/'; // 设置附件上传根目录
                $upload->savePath  =     ''; // 设置附件上传（子）目录
                $upload->replace   =     true;
                $upload->autoSub = false;
                $upload->saveName = 'project_'.I('id');

                // 上传文件
                $info = $upload->upload();

                if(!$info) {
                    $msg = array('status'=>'0','info'=>$upload->getError());
                    exit(json_encode($msg));
                }else{// 上传成功
                    $data['img'] = $info['file']['savename'];
                }
            }

            $res = $Project->save($data);
            if($res !== false){
                $msg = array('status'=>'1','info'=>'项目信息保存成功！','img'=>$data['img']);
            } else {
                $msg = array('status'=>'0','info'=>'数据保存失败！');
            }
        }
		echo json_encode($msg);
		exit;
    }

    public function saveVersion($project_id=0){
        $map['pd.project_id'] = $project_id;
        $list = M('project_design')->alias('pd')
            ->join(C('DB_PREFIX').'project_device d ON pd.project_device_id=d.id')
            ->join(C('DB_PREFIX').'cpn_class_group cg ON d.cpn_type=cg.cpn_type AND d.group_code=cg.group_code')
            ->join(C('DB_PREFIX').'device_class_param cp ON pd.param_id=cp.id')
            ->join('LEFT JOIN '.C('DB_PREFIX').'project_floor f ON d.floor=f.floor AND f.project_id='.$project_id)
            ->join('LEFT JOIN '.C('DB_PREFIX').'device_sensor s ON cp.sensor_type=s.sensor_code')
            ->join('LEFT JOIN '.C('DB_PREFIX').'device_control c ON cp.control_type=c.control_code')
            ->field('d.id,pd.param_id,d.cpn_sn,d.device_sn,d.intro,f.floor_name,cg.group_name,TRIM(cp.sign_name) as sign_name,cp.control_type,cp.sensor_type,cp.control_type_group,cp.sensor_type_group,c.control_name,s.sensor_name,c.sorts')
            ->where($map)
            ->order('d.sort IS NULL,d.sort,d.id,s.sorts')
            ->select();
 
            //按cpn分类
            $lists = $control_sort_arr = array();
            foreach($list as $v){
                $lists[$v['id']][] = $v;
                $control_sort_arr[$v['control_name']] = $v['sorts'];
            }
            $control_sort_arr = array_filter($control_sort_arr);

            $data = $tmp = array();
            foreach($lists as $k=>$v){
                $tmp['cpn_sn'] = $v[0]['cpn_sn'];
                $tmp['group_name'] = $v[0]['group_name'];
                $tmp['device_sn'] = $v[0]['device_sn'];
                $tmp['floor_name'] = $v[0]['floor_name'];
                $tmp['intro'] = $v[0]['intro'];
                $tmp['controls'] = getDeviceControl($k)['sum'];
                $tmp['sensors'] = getDeviceSensor($k);
                $tmp['signs'] = array_count_values(array_column($v, 'sign_name'));
                $data[] = $tmp;
            }

            //取得合并的控制器，和传感器名称
            $controls = $sensors = $sensor_params = array();
            foreach($data as $v){
                $controls = array_merge($controls, array_keys($v['controls']));
                $sensors = array_merge($sensors, array_keys($v['sensors']));
                foreach($v['sensors'] as $k=>$vv){
                    $sensor_params[$k] = array('name'=>$vv['name'], 'param'=>$vv['param_str']);
                }
            }

            $controls = array_unique($controls);
            $sensors = array_unique($sensors);

            //控制器排序
            $control_names = $control_sort_names = $others = array();
            $control_sort_names = array_keys($control_sort_arr);
            foreach($controls as $ctrl){
                if(in_array($ctrl, $control_sort_names)){
                    $control_names[$ctrl] = $control_sort_arr[$ctrl];
                } else {
                    $others[] = $ctrl;
                }
            }
            sort($others);
            asort($control_names);
            $control_names = array_merge($others, array_keys($control_names));
            //控制器排序结束

            $sensor_headers = $names = array();
            foreach($sensors as $k=>$v){
                $sz = explode('#', $v);
                $names[$sz[0]][] = $v;
                $index = array_search($v, $names[$sz[0]]);
                if($index == 0){
                    $sensor_headers[$v] = $sensor_params[$v]['name'];
                } else {
                    $sensor_headers[$v] = $sensor_params[$v]['name'].'-'.$index;
                }
            }

            asort($sensor_headers);

            //自定义信号排序
            /*
            $tmp_sign_names = array_unique(array_column($list, 'sign_name'));

            $sign_sort = array('DI', 'DO', 'AI', 'AO');
            $sign_names = $others = array();
            foreach($tmp_sign_names as $s){
                if(array_search($s, $sign_sort) !== false){
                    $idx = array_search($s, $sign_sort);
                    $sign_names[$idx] = $s;
                } else {
                    $others[] = $s;
                }
            }

            ksort($sign_names);
            $sign_names = array_merge($sign_names, $others);
            */

            //信号排序
            $sign_names = array_unique(array_column($list, 'sign_name'));
            $sign_names = array_filter($sign_names);
            sort($sign_names);

            $headers = array(
                'controls'=>$control_names,
                'sensors'=>$sensor_headers,
                'signs'=>$sign_names
            );

            $vo = M('project')->find($project_id);

            //监控点数据
            $list = M('project_design')->alias('pd')
                ->join(C('DB_PREFIX').'project_device d ON pd.project_device_id=d.id')
                ->join(C('DB_PREFIX').'cpn_class_group g ON d.group_code=g.group_code AND d.cpn_type=g.cpn_type')
                ->join(C('DB_PREFIX').'device_class_param cp ON pd.param_id=cp.id')
                ->field("d.id,d.cpn_sn,d.device_sn,d.floor,d.cpn_type,group_concat(concat(cp.device_param_name,'(',cp.sign_name,')')) as param_name,g.group_name")
                ->group('d.id')
                ->where(array('pd.project_id'=>$project_id))
                ->order('d.sort IS NULL,d.sort,d.id')
                ->select();

            $monitor_data = array();
            foreach($list as $v){
                $monitor_data[$v['group_name']][] = array(
                    'id' => $v['id'],
                    'name' => $v['cpn_sn'],
                    'controls' => getDeviceControl($v['id'])['show_str'],
                    'param_names' => array_unique(explode(',', $v['param_name'])),
                );
            }
            
            $cpn_types = array_column($list, 'cpn_type');
            $cond['t.cpn_type'] = array('in', $cpn_types);
            $cond['t.module_id'] = $vo['module_ids'];

            $fields = M('tpl_module_template')->alias('t')
                ->join(C('DB_PREFIX').'cpn_class_group g ON t.group_code=g.group_code AND t.cpn_type=g.cpn_type')
                ->join(C('DB_PREFIX').'tpl_module_template_param tp ON t.id=tp.template_id')
                ->join(C('DB_PREFIX').'device_class_param cp ON tp.device_param_id=cp.id')
                ->join('LEFT JOIN '.C('DB_PREFIX').'device_sensor s ON cp.sensor_type=s.sensor_code')
                ->field('cp.*,g.group_name')
                ->order('g.cpn_type,g.group_code,tp.id')
                ->where($cond)
                ->select();

            $monitor_columns = array();
            foreach($fields as $f){
                $monitor_columns[$f['group_name']][] = $f['device_param_name'].'('.$f['sign_name'].')';
            }            

            $filename = $project_id . '-' . time();
            $this->makeFile($headers, $data, $vo, $monitor_columns, $monitor_data, $filename);
            $this->makePdf($headers, $data, $vo, $monitor_columns, $monitor_data, $filename);

            //版本信息列表
            $ProjectVersion = M('project_version');
            $intro = I('intro');
            if($filename){
                $dat['project_id'] = $project_id;
                $dat['filename'] = $filename;
                $dat['intro'] = $intro;
                $dat['created_at'] = date('Y-m-d H:i:s');
                $ProjectVersion->add($dat);
            }

            $this->version($project_id);
            
    }

    public function version($project_id=0){
        $ProjectVersion = M('project_version');
        $count = $ProjectVersion->where(array('project_id'=>$project_id))->count();
        $Page  = $this->getpage($count,20);
        $page_tpl = urlencode('[PAGE]'); 
        $Page->url = "javascript:goto($page_tpl)";

        $list = $ProjectVersion
            ->where(array('project_id'=>$project_id))
            ->order('id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

        $lists = array();
        foreach($list as $v){
            $riqi = date('Y-m-d', strtotime($v['created_at']));
            $lists[$riqi][] = $v;
        }
        
        $show  = $this->bootstrap_page_style($Page->show());
        $this->assign('page',$show);
        $this->assign('lists', $lists);
        $content = $this->fetch('version');
        $this->ajaxReturn(array('count'=>$count, 'data'=>$content));
    }

    public function delVersion($id=0){
    	$ProjectVersion = M('project_version');
    	$vo = $ProjectVersion->find($id);
    	$path = dirname(THINK_PATH).'/Uploads/version/'.$vo['filename'];
    	@unlink($path . '.xls');
    	@unlink($path . '.pdf');
    	$ProjectVersion->delete($id);

    	$this->version($vo['project_id']);

    }

    private function makeFile($headers, $data, $info, $monitor_columns, $monitor_data, $filename){
        set_time_limit(0);
        /*
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        */
        // header('Content-Type: application/octet-stream');

        // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		// header('Content-Disposition: attachment;filename="test.xlsx"');
		// header('Cache-Control: max-age=0');
        import("Org.Util.PHPExcel");
        /*
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
		$cacheSettings = array('memoryCacheSize'=>'16MB');
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
*/

        $rendererName = \PHPExcel_Settings::PDF_RENDERER_MPDF;
        $rendererLibrary = 'mpdf';
        $rendererLibraryPath = './ThinkPHP/Library/Vendor/' . $rendererLibrary;

        $objPHPExcel = new \PHPExcel();
		$objPHPExcel->getProperties()->setCreator("邻元科技")
							 ->setLastModifiedBy("邻元科技")
							 ->setTitle("群智能系统设计选型结果")
							 ->setSubject("群智能系统设计选型结果")
							 ->setDescription("群智能系统设计选型结果")
							 ->setKeywords("选型结果")
                             ->setCategory("邻元科技");
        
        $sheet = $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle('汇总');

        //$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
        //$objPHPExcel->getDefaultStyle()->getFont()->setSize(20);

        $styleThinBlackBorderOutline = array(
            'borders' => array(
                'allborders' => array( //设置全部边框
                    'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                ),
            ),
            'alignment' => array (
                'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
            ),
        );

        $styleThinBlackBorder = array(
            'borders' => array(
                'allborders' => array( //设置全部边框
                    'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                ),
            ),
            'alignment' => array (
                'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
            ),
        );

        //表头
        $sheet->setCellValue('C3', '项目编号：'.$info['project_code'])
            ->setCellValue('F3', '项目地点：'.$info['project_addr'])
            ->setCellValue('M3', '设计阶段：'.$info['project_progress'])
            ->setCellValue('T3', '导出时间：'.date('Y-m-d H:i:s'));

        $sheet->setCellValue('C5', '序号')
            ->setCellValue('D5', 'CPN编号')
            ->setCellValue('E5', '专用控制器类型')
            ->setCellValue('F5', '被控设备编号或数量')
            ->setCellValue('G5', '安装楼层')
            ->setCellValue('H5', '备注')
            ->setCellValue('I5', '控制模块选型结果');
        
        $sheet->getColumnDimension('D')->setWidth(22);
        $sheet->getColumnDimension('E')->setWidth(11);
        $sheet->getColumnDimension('F')->setWidth(11);
        $sheet->getColumnDimension('G')->setWidth(11);
        $sheet->getColumnDimension('H')->setWidth(11);
            
        //控制器表头
        $x = 8;
        foreach($headers['controls'] as $c){
            $letter = $this->stringFromColumnIndex($x);
            $sheet->setCellValue($letter.'6', $c);

            $sheet->getColumnDimension($letter)->setWidth(7);
            $x++;
        }

        //传感器表头
        foreach($headers['sensors'] as $s){
            $letter = $this->stringFromColumnIndex($x);
            $sheet->setCellValue($letter.'6', $s);

            //$len = strlen($s);
            //$sheet->getColumnDimension($letter)->setWidth($len);
            $sheet->getColumnDimension($letter)->setWidth(7);
            $x++;
        }

        //信号表头
        foreach($headers['signs'] as $n){
            $letter = $this->stringFromColumnIndex($x);
            $sheet->setCellValue($letter.'6', $n);
            $sheet->getColumnDimension($letter)->setWidth(7);
            $x++;
        }

        $sheet->mergeCells('C5:C6')
            ->mergeCells('D5:D6')
            ->mergeCells('E5:E6')
            ->mergeCells('F5:F6')
            ->mergeCells('G5:G6')
            ->mergeCells('H5:H6');
        
        //控制表头合并
        $colspan1_end = 7 + count($headers['controls']);
        $letter = $this->stringFromColumnIndex($colspan1_end);
        $sheet->mergeCells('I5:'.$letter.'5');

        //传感器表头合并
        $colspan2_start = $colspan1_end + 1;
        $colspan2_end = $colspan2_start + count($headers['sensors']) - 1;

        $letter_start = $this->stringFromColumnIndex($colspan2_start);
        $letter_end = $this->stringFromColumnIndex($colspan2_end);
        $sheet->setCellValue($letter_start.'5', '传感器、执行器等选型结果');
        $sheet->mergeCells($letter_start.'5:'.$letter_end.'5');
        
        //信号表头合并
        $colspan3_start = $colspan2_end + 1;
        $colspan3_end = $colspan3_start + count($headers['signs']) - 1;

        $letter_start = $this->stringFromColumnIndex($colspan3_start);
        $letter_end = $this->stringFromColumnIndex($colspan3_end);
        $sheet->setCellValue($letter_start.'5', '监控点位数量');
        $sheet->mergeCells($letter_start.'5:'.$letter_end.'5');

        //表格标题
        $sheet->setCellValue('C1', $info['project_name'].'项目群智能系统设计选型结果');
        $sheet->mergeCells('C1:'.$letter_end.'1');

        //开始数据显示
        $y = 7;
        $i = 1;
        $param_arr = array();
        foreach($data as $cpn=>$v){
            //获取传感器参数
            foreach($v['sensors'] as $k=>$vv){
                $param_arr[$k] = $vv['param_str'];
            }

            $sheet->setCellValue('C'.$y, $i++)
                ->setCellValue('D'.$y, $v['cpn_sn'])
                ->setCellValue('E'.$y, $v['group_name'])
                ->setCellValue('F'.$y, $v['device_sn'])
                ->setCellValue('G'.$y, $v['floor_name'])
                ->setCellValue('H'.$y, $v['intro']);
            
            $col = 8;
            foreach($headers['controls'] as $h){
                $letter = $this->stringFromColumnIndex($col);
                $zhi = empty($v['controls'][$h]) ? 0 : $v['controls'][$h];
                $sheet->setCellValue($letter.$y, $zhi);
                $col++;
            }

            foreach($headers['sensors'] as $k=>$h){
                $letter = $this->stringFromColumnIndex($col);
                $zhi = empty($v['sensors'][$k]) ? 0 : $v['sensors'][$k]['count'];
                $sheet->setCellValue($letter.$y, $zhi);
                $col++;
            }

            foreach($headers['signs'] as $h){
                $letter = $this->stringFromColumnIndex($col);
                $zhi = empty($v['signs'][$h]) ? 0 : $v['signs'][$h];
                $sheet->setCellValue($letter.$y, $zhi);
                $col++;
            }
            $y++;
        }

        //Total
        $sheet->setCellValue('C'.$y, '总计');
        $sheet->mergeCells('C'.$y.':G'.$y);

        $sheet->getStyle('C'.$y.':'.$letter.$y)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $sheet->getStyle('C'.$y.':'.$letter.$y)->getFill()->getStartColor()->setARGB('FF00FF00');

        //总计 公式
        for($i = 8; $i < $col; $i++){
            $letter = $this->stringFromColumnIndex($i);
            $n = $y - 1;
            $sheet->setCellValue($letter.$y, "=SUM({$letter}7:{$letter}$n)");
        }

        //表格线，文字居中
        $highest_column = $sheet->getHighestColumn();
        $sheet->getStyle('C5:'.$highest_column.$y)->applyFromArray($styleThinBlackBorderOutline);
        $sheet->getStyle('C5:'.$highest_column.$y)->getAlignment()->setWrapText(true);

        //传感器参数显示
        $canshu_row = ++$y;

        $sheet->setCellValue('C'.$y, '传感器、执行器等选型参数要求说明：');
        $sheet->mergeCells('C'.$y.':'.$highest_column.$y);
        $y++;
        $content = '';
        foreach($headers['sensors'] as $k=>$v){
            $content = $v . "：" . str_replace("#", "    ", $param_arr[$k]);
            $sheet->setCellValue('C'.$y, $content);
            $sheet->mergeCells('C'.$y.':'.$highest_column.$y);
            $y++;
        }

        //$content .= $v . "：" . str_replace("#", "    ", $param_arr[$k]) . "\n";
        //$sheet->getStyle('C'.$y)->getAlignment()->setWrapText(true);
        

        $y--;
        $sheet->getStyle( 'C'.$canshu_row.':'.$highest_column.$y)->applyFromArray($styleThinBlackBorder);
        $sheet->getStyle('C1')
            ->getFont()
            ->setName('微软雅黑')    //设置字体
            ->setSize(16)          //设置字体大小 
            ->setBold(true);         //是否家加粗
        //     ->setItalic(true);      //是否斜体
        // ->getColor()->setRGB('FF0000');
        $sheet->getStyle('C1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        //监控点表
        $j = 1;
        foreach($monitor_columns as $group=>$v){
            if(empty($monitor_data[$group])) continue;
            $objPHPExcel->createSheet();
            $sheet = $objPHPExcel->setActiveSheetIndex($j);
            $objPHPExcel->getActiveSheet()->setTitle($this->filterSheetName($group).'监控点表');

            $sheet->setCellValue('C2', $group.'专用控制器监控点表')
				->setCellValue('C4', '序号')
				->setCellValue('D4', 'CPN编号')
                ->setCellValue('E4', '专用控制器配置');

            $sheet->getColumnDimension('E')->setWidth(22);
            
            //数据列名
            $col = 5;
            foreach($v as $vv){
                $letter = $this->stringFromColumnIndex($col);
                $sheet->setCellValue($letter.'4', $vv);

                //$len = strlen($vv);
                //$sheet->getColumnDimension($letter)->setWidth($len);
                $sheet->getColumnDimension($letter)->setWidth(6);
                $col++;
            }

            $row = 5;
            $x = 1;
            
            foreach($monitor_data[$group] as $d){
                $col = 5;
                
                $sheet->setCellValue('C'.$row, $x)
                    ->setCellValue('D'.$row, $d['name'])
                    ->setCellValue('E'.$row, $d['controls']);

                foreach($monitor_columns[$group] as $param_name){
                    $letter = $this->stringFromColumnIndex($col);
                    if(in_array($param_name, $d['param_names'])) $sheet->setCellValue($letter.$row, '√');
                    $col++;
                }
                $x++;
                $row++;
            }

            $row--;
            $highest_column = $sheet->getHighestColumn();
            $sheet->getStyle('C4:'.$highest_column.$row)->applyFromArray($styleThinBlackBorderOutline);
            $sheet->getStyle('C4:'.$highest_column.$row)->getAlignment()->setWrapText(TRUE);
            $sheet->getStyle('C2')
                ->getFont()
                ->setName('微软雅黑')    //设置字体
                ->setSize(16)          //设置字体大小 
                ->setBold(true);

            $sheet->mergeCells('C2:'.$highest_column.'2');
            //$sheet->getStyle('C2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $j++;
        }

        $objPHPExcel->setActiveSheetIndex(0);

        //$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $path = dirname(THINK_PATH).'/Uploads/version/'.$filename.'.xls';

        $objWriter->save($path);

       
       /*
        if (!\PHPExcel_Settings::setPdfRenderer(
            $rendererName,
            $rendererLibraryPath
        )) {
            die(
                'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
                '<br />' .
                'at the top of this script as appropriate for your directory structure'
            );
        }

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment;filename="aaa.pdf"');
        header('Cache-Control: max-age=0');

        $objPHPExcel->getActiveSheet()->setShowGridLines(false);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
        $objWriter->save("php://output");
      */

        return true;
        
    }

    public function makePdf($headers, $data, $info, $monitor_columns, $monitor_data, $filename){
        set_time_limit(0);
        $this->assign('headers', $headers);
        $this->assign('data', $data);
        $this->assign('info', $info);
        $this->assign('monitor_columns', $monitor_columns);
        $this->assign('monitor_data', $monitor_data);
        $strContent = $this->fetch('pdf');

        //引入类库
        Vendor('mpdf.mpdf');
        //设置中文编码
        //$mpdf=new mPDF('utf-8','A4','','宋体',0,0,20,10);
        $mpdf=new \mPDF('zh-cn','A4-L', 0, '宋体', 0, 0);
        $mpdf->SetWatermarkText('邻元科技（北京）科技有限公司', 0.1);
        $mpdf->showWatermarkText = true;
        //$mpdf->CurOrientation = "L";
        
        /*
        //设置PDF页眉内容
        $header='<table width="95%" style="margin:0 auto;border-bottom: 1px solid #4F81BD; vertical-align: middle; font-family:
        serif; font-size: 9pt; color: #000088;"><tr>
        <td width="10%"></td>
        <td width="80%" align="center" style="font-size:16px;color:#A0A0A0">页眉</td>
        <td width="10%" style="text-align: right;"></td>
        </tr></table>';
        
        //设置PDF页脚内容
        $footer='<table width="100%" style=" vertical-align: bottom; font-family:
        serif; font-size: 9pt; color: #000088;"><tr style="height:30px"></tr><tr>
        <td width="10%"></td>
        <td width="80%" align="center" style="font-size:14px;color:#A0A0A0">页脚</td>
        <td width="10%" style="text-align: left;">页码：{PAGENO}/{nb}</td>
        </tr></table>';
        
        //添加页眉和页脚到pdf中
        $mpdf->SetHTMLHeader($header);
        $mpdf->SetHTMLFooter($footer);
        */

        //设置pdf显示方式
        //$mpdf->SetDisplayMode('fullpage');

        
        //设置pdf的尺寸为270mm*397mm
        //$mpdf->WriteHTML('<pagebreak sheet-size="270mm 397mm" />');

        $mpdf->WriteHTML($strContent);

        //删除pdf第一页(由于设置pdf尺寸导致多出了一页)
        //$mpdf->DeletePages(1,1);


        $path = dirname(THINK_PATH).'/Uploads/version/'.$filename.'.pdf';

        $mpdf->Output($path);
        //直接浏览器输出pdf
        //$mpdf->Output('tmp.pdf',true);
        //$mpdf->Output('contract.pdf','d');
        //$mpdf->Output();
    }

    public function download($id=0, $ext='xls'){
        if(empty(session(C('SESSION_ADMIN_ID')))) exit('<script>alert("请先登录！");</script>');
        $ext = strtolower($ext);
        $map['v.id'] = $id;
        $vo = M('project_version')->alias('v')
            ->join(C('DB_PREFIX').'project p ON v.project_id=p.id')
            ->field('p.project_name,v.filename')
            ->where($map)
            ->find();
        
        $filename = $vo['filename'];
        
        if($ext == 'xls'){
            $filename = $vo['filename'].'.xls';
            header('Content-Type: application/vnd.ms-excel');
        } elseif($ext == 'pdf'){
            $filename = $vo['filename'].'.pdf';
            header('Content-Type: application/pdf');
        }

        $name = $vo['project_name'].date('Y-m-d-His') . '.' . $ext;
        $path = dirname(THINK_PATH).'/Uploads/version/'.$filename;
        $filesize = filesize($path);

        header("Accept-Ranges: bytes");
        header("Accept-Length:".$filesize ); 
        header("Content-Disposition: attachment; filename=".$name);

        $handle = fopen($path, "rb"); 
        echo fread($handle, $filesize);
        fclose($handle);
    }

    public function saveSort(){
		$data = I('data');
		$ProjectDevice = M('project_device');
		foreach($data as $v){
			$ProjectDevice->where(array('id'=>$v['id']))->setField('sort', $v['sort']);
		}
		echo '1';
	}
    
    private function isAdmin($user_id){
        $map['userid'] = $user_id;
        $is_admin = M('member')->where($map)->getField('is_admin');
        if($is_admin == 1){
            return true;
        } else {
            return false;
        }
    }

    private function isProjectAdmin($project_id){
        $uid = session(C('SESSION_ADMIN_ID'));
        $user_id = M('project')->where(array('id'=>$project_id))->getField('user_id');
        return $uid == $user_id ? true : false;
    }

    private function getSensorNum($project_id){
        $map['project_id'] = $project_id;
        $list = M('project_device')->where($map)->getField('id', true);

        $num = 0;
        foreach($list as $device_id){
            $param_list = getDeviceSensorParam($device_id);
            $num += count($param_list);
        }

        return $num;
    }

    private function getNames($list, $type, $type_group, $params=[]){
        $json = json_encode($params);
        $data = $tmp = array();
        foreach($list as $v){
            if($type == 'sensor_type'){
                $str = $v[$type].'-'.$v[$type_group].'-'.$json;
            } else {
                $str = $v[$type].'-'.$v[$type_group];
            }

            $tmp[] = $str;
        }

        $tmp = array_unique($tmp);

        return $tmp;
    }

    private function getCount1($list, $type, $type_group){
        $data = $tmp = array();
        foreach($list as $v){
            $tmp[$v['cpn_sn']][$v[$type].'-'.$v[$type_group]][] = $v[$type_group];
        }

        foreach($tmp as $cpn=>$arr){
            foreach($arr as $k=>$v)
            $data[$cpn][$k] = count(array_unique($v));
        }

        return $data;
    }

    private function getParams($device_id){

         //传感器参数
         $cond['device_id'] = $device_id;
         $plist = M('project_device_sensor_param')->alias('p')
             ->join(C('DB_PREFIX').'device_sensor_param sp ON p.sensor_param_id=sp.id')
             ->field('sp.id,sp.sensor_param_name,sp.sensor_param_value,sp.sensor_param_range,sp.sensor_param_unit,p.sensor_code,p.sensor_type_group,p.value')
             ->where($cond)
             ->order('sp.id')
             ->select();
 
         $sensors_params = array();
         foreach($plist as $p){
             $sensors_params[$p['sensor_code'].'_'.$p['sensor_type_group']][] = $p;
         }
    }

    private function stringFromColumnIndex($pColumnIndex = 0){ 
        static $_indexCache = array(); 
  
        if (!isset($_indexCache[$pColumnIndex])) { 
            // Determine column string 
            if ($pColumnIndex < 26) { 
                $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex); 
            } elseif ($pColumnIndex < 702) { 
                $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) . chr(65 + $pColumnIndex % 26); 
            } else {
                $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) . chr(65 + ((($pColumnIndex - 26) % 676) / 26)) . chr(65 + $pColumnIndex % 26); 
            } 
        } 
        return $_indexCache[$pColumnIndex]; 
    }
    
    private function filterSheetName($name){
        //sheet名称不能多于31个（包含英文、汉字、| 、（）等，但是不能包含 ：\ / ？ * [ ]等 )
        return str_replace(array('\\', '/', '?', '*', '[', ']'), ' ', $name);
    }

}